import { apiClient, apiRoutes } from "../../utils/api"

// pages/cameras/cameras.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cameras:[],
    online:{}
  },
  fetch_data(){
    apiClient.get(apiRoutes.cameras).then(res => {
      if (res.data.length != 0) {
        // 创建一个Promise数组
        let promises = res.data.map((item, i) => {
          item.online = false;
          return new Promise((resolve, reject) => {
            wx.request({
              method: 'HEAD',
              url: apiRoutes.hls + item.stream + '.m3u8',
              success: (response) => {
                console.log("head", response.statusCode);
                if (response.statusCode == 200) {
                  item.online = true;
                }
                resolve();
              },
              fail: (error) => {
                console.error("HEAD request failed", error);
                resolve(); // 确保失败时也resolve，避免影响其他请求
              }
            });
          });
        });
    
        // 等待所有请求完成
        Promise.all(promises).then(() => {
          this.setData({ cameras: res.data });
          console.log(this.data.cameras); // 注意这里应该是this.data.cameras
        });
      }
    }).catch(err => {
      console.log(err);
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.fetch_data()
    if(this.data.cameras != 0){
      console.log(this.data.cameras, this.data.cameras.length)
    }else{
      console.log('no') 
    }
  },

})